package com.util.vmwareops;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

public class DatastoreOps {
    public static synchronized void updateDatastore(Connection con, Map<String, DatastoreInfo> datastoreInfoMap, String versionId) throws SQLException {

        Statement st = con.createStatement();
        for(DatastoreInfo datastoreInfo : datastoreInfoMap.values()) {
            String sql_command = String.format(
                    "insert into resource_bundle_vsphere_datastore values(\"%s\", \"%s\", \"%s\", %.2f, %.2f, %.2f, \"%s\")",
                    datastoreInfo.getId(),
                    datastoreInfo.getVc().getId(),
                    datastoreInfo.getDatastoreName(),
                    datastoreInfo.getTotalCapacity(),
                    datastoreInfo.getProvisionedSpace(),
                    datastoreInfo.getFreeSpace(),
                    datastoreInfo.getVersionId()
            );
            st.execute(sql_command);
        }
    }
    
    public static Map<String, DatastoreInfo> getDatastoreInfoByVersionId(String versionId) throws InterruptedException {
        DBConnectionPool db = DBConnectionPoolFactory.getDBConnectionPool("vmwareops");
        Connection con = db.getConnection();
        Map<String, DatastoreInfo> datastoreInfos = new HashMap<String, DatastoreInfo>();
        String sql = String.format("select * from %s where version=\'%s\'", "resource_bundle_vsphere_datastore", versionId);
        try {
            Statement stmt = con.createStatement();
            ResultSet res = stmt.executeQuery(sql);
            if(res == null) {
                return null;
            }
            while(res.next()) {
                datastoreInfos.put(
                        res.getString("id"),
                        new DatastoreInfo(
                                res.getString("id"),
                                null,
                                res.getString("datastore_domain_name"),
                                res.getDouble("total_capacity"),
                                res.getDouble("provisioned_space"),
                                res.getDouble("free_space"),
                                res.getString("version")
                        )
                );
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(con != null) {
                db.close(con);
            }
        }
        return datastoreInfos;
    }
}
